/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.mongoservice;

import cn.ac.iie.di.wx.vo.FansUpdateVo;
import java.util.HashMap;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;

/**
 *
 * @author Administrator
 */
public class FansMongoThread implements Runnable {

    public MongoHelper mongoHelper;
    public LinkedBlockingQueue<FansUpdateVo> fansBlockingQueue;
    public static Logger logger = Logger.getLogger(FansMongoThread.class.getName());

    public FansMongoThread(MongoHelper mongoHelper, LinkedBlockingQueue<FansUpdateVo> blockingQueue) {
        this.mongoHelper = mongoHelper;
        this.fansBlockingQueue = blockingQueue;
    }

    public MongoHelper getMongoHelper() {
        return mongoHelper;
    }

    public void setMongoHelper(MongoHelper mongoHelper) {
        this.mongoHelper = mongoHelper;
    }

    @Override
    public void run() {
        //handler 中将tx的返回值放入队列中，这个线程用于处理mongo入库，避免重复创建连接
        //先查出来需要更新的列，再根据字段更新相应的值
        while (true) {
            try {
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                for (int i = 0; i < 10; i++) {
                    FansUpdateVo vo = fansBlockingQueue.poll(1000, TimeUnit.SECONDS);
                    if (vo != null) {
                        hashMap.put(vo.getId(), Long.parseLong(vo.getNfans()));
                    }
                }
                if (!hashMap.isEmpty()) {
                    mongoHelper.update("_id", "nfans", hashMap);
                    logger.info("update fansCount to wxuser mongoDB");
                }

            } catch (InterruptedException ex) {
                logger.error(ex.getMessage(), ex);
            }
        }

    }
    public static void main(String[] args) throws InterruptedException {
        LinkedBlockingQueue<String> test=new LinkedBlockingQueue(200);
        int i=1;
        while(test.size()<=199){
            test.add("test"+i);
            ++i;
        }
        while(!test.isEmpty()){
//            System.err.println(test.poll(1000, TimeUnit.SECONDS));
            logger.info(test.poll(1000, TimeUnit.SECONDS));
        }
    }
}
